package com.schoolhelper.model.dao.okhttp;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.schoolhelper.utils.constant.Api;
import com.schoolhelper.model.entity.User;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import lombok.SneakyThrows;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class RequestUtil {

    public static final String OK_MSG= "执行成功";

    @SneakyThrows
    public static <T> List<T> getAll(String baseUrl, String api, Class<T> t) {
        List<T> list = new ArrayList<>();
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(baseUrl + "/" + api)
                .get()
                .build();
        Response response = client.newCall(request).execute();

        String responseData = Objects.requireNonNull(response.body()).string();

        JSONObject responseJson = (JSONObject) JSONObject.parse(responseData);
        if (OK_MSG.equals(responseJson.get("msg"))) {
            JSONObject dataJson = (JSONObject) responseJson.get("data");
            if (dataJson != null) {
                JSONArray recordsArray = (JSONArray) dataJson.get("records");
                for (int i = 0; i < Objects.requireNonNull(recordsArray).size(); i++) {
                    JSONObject data = recordsArray.getJSONObject(i);
                    list.add(JSON.parseObject(String.valueOf(data), t));
                }
            } else {
                System.out.println("error: " + "数据库中无对应数据");
            }
        } else {
            System.out.println("error: " + responseJson.get("error"));
        }
        return list;
    }

    @SneakyThrows
    public static <T> T getById(String baseUrl, String api, long id, Class<T> t) {
        T t1 = null;
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(baseUrl + "/" + api + "/" + id)
                .get()
                .build();
        Response response = client.newCall(request).execute();

        String responseData = Objects.requireNonNull(response.body()).string();

        JSONObject responseJson = (JSONObject) JSONObject.parse(responseData);
        if (OK_MSG.equals(responseJson.get("msg"))) {
            JSONObject dataJson = (JSONObject) responseJson.get("data");
            if (dataJson != null) {
                t1 = JSON.parseObject(String.valueOf(dataJson), t);
            } else {
                System.out.println("error: " + "数据库中无对应数据");
            }
        } else {
            System.out.println("error: " + responseJson.get("error"));
        }
        return t1;
    }

    @SneakyThrows
    public static <T> boolean post(String baseUrl, String api, T t) {
        String json = JSON.toJSONString(t);
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(baseUrl + "/" + api)
                .post(RequestBody.create(MediaType.parse("application/json"), json))
                .build();
        Response response = client.newCall(request).execute();

        String responseData = response.body().string();

        JSONObject responseJson = (JSONObject) JSONObject.parse(responseData);
        if (OK_MSG.equals(responseJson.get("msg"))) {
            return true;
        }
        return false;
    }

    @SneakyThrows
    public static <T> boolean put(String baseUrl, String api, T t) {
        String json = JSON.toJSONString(t);
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(baseUrl + "/" + api)
                .put(RequestBody.create(MediaType.parse("application/json"), json))
                .build();
        Response response = client.newCall(request).execute();

        String responseData = response.body().string();

        JSONObject responseJson = (JSONObject) JSONObject.parse(responseData);
        if (OK_MSG.equals(responseJson.get("msg"))) {
            return true;
        }
        return false;
    }

    @SneakyThrows
    public static boolean delete(String baseUrl, String api, List<Long> idList) {
        FormBody.Builder params = new FormBody.Builder();
        for (Long id : idList) {
            params.add(Api.ID_LIST, String.valueOf(id));
        }
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(baseUrl + "/" + api)
                .delete(params.build())
                .build();
        Response response = client.newCall(request).execute();

        String responseData = response.body().string();

        JSONObject responseJson = (JSONObject) JSONObject.parse(responseData);
        if (OK_MSG.equals(responseJson.get("msg"))) {
            return true;
        }
        return false;
    }

    /**
     * 查询一个表里的所有元组
     * 用例:
     * List<User> users = getAll(Api.USER, User.class);
     * for (User user: users) {
     *     System.out.println(user);
     * }
     *
     * @param api
     * @param t
     * @param <T>
     * @return
     */
    public static <T> List<T> getAll(String api, Class<T> t) {
        return getAll(Api.BASE_URL, api, t);
    }

    /**
     * 根据id查询对应元组
     * 用例：
     * User user = getById(Api.USER, 1, User.class);
     * System.out.println(user);
     *
     * @param api
     * @param id
     * @param t
     * @param <T>
     * @return
     */
    public static <T> T getById(String api, long id, Class<T> t) {
        return getById(Api.BASE_URL, api, id, t);
    }

    /**
     * 新增一个元组
     * 用例：
     * User user2 = new User(null, "赵六", "123456", "0", null, "12312345678", null, "100");
     * if (post(Api.USER, user2)) {
     *     System.out.println("新增成功");
     * }
     *
     * @param api
     * @param t
     * @param <T>
     * @return
     */
    public static <T> boolean post(String api, T t) {
        return post(Api.BASE_URL, api, t);
    }

    /**
     * 更新一个元组
     * 用例：
     * User user3 = new User(9, "赵六", "123456", "0", null, "12312345678", null, "100");
     * if (put(Api.USER, user3)) {
     *     System.out.println("更新成功");
     * }
     *
     * @param api
     * @param t
     * @param <T>
     * @return
     */
    public static <T> boolean put(String api, T t) {
        return put(Api.BASE_URL, api, t);
    }

    /**
     * 根据idList删除元组
     * 用例：
     * List<Long> list = new ArrayList<>(Arrays.asList(0L, 1L));
     * if (delete(Api.USER, list)) {
     *     System.out.println("删除成功");
     * }
     *
     * @param api
     * @param idList
     * @return
     */
    public static boolean delete(String api, List<Long> idList) {
        return delete(Api.BASE_URL, api, idList);
    }

    @Test
    public void testAll() {
        System.out.println("查询所有user");
        List<User> users = getAll(Api.USER, User.class);
        for (User user : users) {
            System.out.println(user);
        }

        System.out.println("\n根据id查询user");
        User user1 = getById(Api.USER, 1, User.class);
        System.out.println(user1);

        System.out.println("\n新增user");
        User user2 = new User(null, "赵六", "123456", "0",
                null, "12312345678", null, null, 100);
        if (post(Api.USER, user2)) {
            System.out.println("新增成功");
        } else {
            System.out.println("新增失败");
        }

        System.out.println("\n更新user");
        User user3 = new User(0, "赵六", "123456", "0",
                null, "12312345678", null, null, 100);
        if (put(Api.USER, user3)) {
            System.out.println("更新成功");
        } else {
            System.out.println("更新失败");
        }

        System.out.println("\n根据id删除user");
        List<Long> list = new ArrayList<>(Arrays.asList(0L, 1L));
        if (delete(Api.USER, list)) {
            System.out.println("删除成功");
        } else {
            System.out.println("删除失败");
        }
    }
}
